package com.stiove.whwh.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.stiove.whwh.dao.mapper.UserMapper;
import com.stiove.whwh.dao.pojo.User;
import com.stiove.whwh.service.AdminService;
import com.stiove.whwh.service.UserService;
import com.stiove.whwh.utils.JWTUtils;
import com.stiove.whwh.utils.SampleUtils;
import com.stiove.whwh.utils.UserThreadLocal;
import com.stiove.whwh.vo.Result;
import com.stiove.whwh.vo.params.UserLoginParams;
import lombok.SneakyThrows;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import sun.security.provider.MD5;

import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class AdminServiceImpl implements AdminService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserServiceImpl userService;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Override
    public Result adminLogin(String username, String password) {
        LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(User::getUsername,username);
        wrapper.eq(User::getPassword, DigestUtils.md5Hex(password));
        wrapper.last("limit 1");
        User userInfo = userMapper.selectOne(wrapper);

        if (userInfo == null){
            return new Result(Result.USER_ERROR,"密钥或密码错误");
        }

        if (userInfo.getIsAdmin() != 1){
            return new Result(Result.USER_ERROR,"密钥或密码错误",userInfo.getId());
        }

        String token = JWTUtils.createToken(userInfo.getId());

        redisTemplate.opsForValue().set(token, JSON.toJSONString(userInfo));
        return new Result(Result.SUCCESS,"成功",token);
    }



}
